package com.yonyou.distribute.service;

import com.yonyou.distribute.mapper.StockMapper;
import com.yonyou.distribute.pojo.Stock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * p13 p14
 * mysql悲观锁解决库存超卖
 *
 * mysql悲观锁使用行锁
 * 1、锁的查询或者更新字段必须是索引字段
 * 2、查询或者更新的条件必须是具体值
 *
 * 缺点：
 * 1、性能问题
 * 2、死锁问题，对多条数据加锁时，加锁顺序一致；比如 a对id=1加锁，b对id=2加锁，a在对id=2加锁时，会导致死锁
 * 3、
 */
@Slf4j
@Service
public class MysqlService_5 {


    @Resource
    private StockMapper stockMapper;

    @Value("${server.port}")
    private Integer port;

    @Transactional
    public void deduct(){

        // 1、查询库存
        List<Stock> stocks = this.stockMapper.queryStock("1001");
        Stock stock = stocks.get(0);
        // 2、判断库存是否充足
        if(null != stock && stock.getCount() > 0){
            stock.setCount(stock.getCount() - 1);
            System.out.println("剩余库存：" + stock.getCount() + "--" + port);

            //3、更新库存到数据库
            this.stockMapper.updateById(stock);
        }
    }
}
